package cn.huiyunche.base.service.interfaces.impl;

import cn.huiyunche.base.service.enums.TruckAuditStatusEnum;
import cn.huiyunche.base.service.exception.CustomizeException;
import cn.huiyunche.base.service.framework.utils.HYCUtils;
import cn.huiyunche.base.service.framework.utils.QiniuUtils;
import cn.huiyunche.base.service.interfaces.DriverCertInfoService;
import cn.huiyunche.base.service.interfaces.UserService;
import cn.huiyunche.base.service.mappers.CDriverCertinfoMapper;
import cn.huiyunche.base.service.mappers.CTruckInfoMapper;
import cn.huiyunche.base.service.model.*;
import cn.huiyunche.base.service.vo.DriverCertInfoVo;
import cn.huiyunche.base.service.vo.UserUpdateVo;
import cn.huiyunche.base.service.vo.UserVo;
import cn.huiyunche.tools.basic.exceptions.BusinessException;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service

public class DriverCertInfoServiceImpl implements DriverCertInfoService {

    private static final Logger LOGGER = LoggerFactory.getLogger(DriverCertInfoServiceImpl.class);

    @Autowired
    private UserService userService = null;

    @Autowired
    private CTruckInfoMapper cTruckInfoMapper = null;

    private CTruckInfoMapper getCTruckInfoMapper() {
        return this.cTruckInfoMapper;
    }

    @Autowired
    private CDriverCertinfoMapper cDriverCertinfoMapper = null;

    private UserService getUserService() {
        return this.userService;
    }

    private CDriverCertinfoMapper getCDriverCertinfoMapper() {
        return this.cDriverCertinfoMapper;
    }

    @Override
    public DriverCertInfoVo list(Boolean truckType) throws Exception {
        LOGGER.info("Start to perform DriverCertInfoServiceImpl in the list method ...... ");
        UserVo user = this.getUserService().getCurrentUserVo();
        LOGGER.info("user id : {}", user.getId());
        CDriverCertinfoExample example = new CDriverCertinfoExample();
        CDriverCertinfoExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(user.getId());
        List<CDriverCertinfo> certinfos = this.getCDriverCertinfoMapper().selectByExample(example);
        DriverCertInfoVo vo = new DriverCertInfoVo();
        if (CollectionUtils.isNotEmpty(certinfos) && certinfos.size() > 0) {
            BeanUtils.copyProperties(certinfos.get(0), vo);
            vo.setIdpicUrl1(QiniuUtils.generateDownloadTicket(vo.getIdpic1(), ""));
            vo.setIdpicUrl2(QiniuUtils.generateDownloadTicket(vo.getIdpic2(), ""));
            if (StringUtils.isNotBlank(vo.getIdno())) {
                String idno = HYCUtils.decryptAppSensitiveInformation(vo.getIdno());
                vo.setIdno(idno);
                vo.setShowIdno(idno.substring(0, 6) + "********" + idno.substring(idno.length() - 4, idno.length()));
            }
            // 司机认证状态取车辆认证状态
            int status = this.queryTruckInfoStatus(user.getId(), truckType);
            vo.setStatusText(TruckAuditStatusEnum.getByValue(status).getText());
            vo.setStatus(status);
            SUser sUser = this.getUserService().getById(user.getId());
            vo.setRealName(sUser.getRealName());
        } else {
            vo = null;
        }
        LOGGER.info("perform DriverCertInfoServiceImpl in the list method end ");
        return vo;
    }

    /**
     * 查询车辆审核状态
     *
     * @param userId
     * @param truckType
     * @throws BusinessException
     */
    private int queryTruckInfoStatus(Long userId, Boolean truckType) throws Exception {
        CTruckInfoExample example = new CTruckInfoExample();
        example.createCriteria().andUserIdEqualTo(userId).andTruckTypeEqualTo(truckType == null ? false : truckType);
        List<CTruckInfo> lists = this.getCTruckInfoMapper().selectByExample(example);
        if (CollectionUtils.isNotEmpty(lists)) {
            return lists.get(0).getStatus();
        } else {
            return TruckAuditStatusEnum.NOT_SUBMIT.getValue();
        }
    }

    @Override
    public long add(DriverCertInfoVo driverCertInfoVo) throws Exception {
        UserVo vo = this.getUserService().getCurrentUserVo();
        CDriverCertinfo certinfo = new CDriverCertinfo();
        BeanUtils.copyProperties(driverCertInfoVo, certinfo);
        String idno = HYCUtils.encryptBankCard(certinfo.getIdno());
        driverCertInfoVo.setUserId(vo.getId());
        CDriverCertinfoExample example = new CDriverCertinfoExample();
        example.createCriteria().andIdnoEqualTo(idno);
        List<CDriverCertinfo> cList = this.getCDriverCertinfoMapper().selectByExample(example);
        if (cList.size() > 0) {
            LOGGER.info("The idno information already exists");
            throw new BusinessException("身份证号已认证");
        }
        certinfo.setIdno(idno);
        certinfo.setUserId(vo.getId());
        certinfo.setStatus(TruckAuditStatusEnum.NOT_SUBMIT.getValue());
        try {
            this.getCDriverCertinfoMapper().insertSelective(certinfo);
        } catch (Exception e) {
            LOGGER.error("insert driverCertinfo error: {}", e);
            throw new BusinessException("司机认证失败");
        }
        UserUpdateVo user = new UserUpdateVo();
        user.setRealname(driverCertInfoVo.getRealName());
        try {
            this.getUserService().updateById(user);
        } catch (Exception e) {
            LOGGER.error("update user info error : {}", e);
            throw new BusinessException("更新用户信息失败");
        }
        return certinfo.getId();
    }

    @Override
    public int update(DriverCertInfoVo driverCertInfoVo) throws Exception {
        UserVo vo = this.getUserService().getCurrentUserVo();
        driverCertInfoVo.setUserId(vo.getId());
        CDriverCertinfo certinfo = new CDriverCertinfo();
        BeanUtils.copyProperties(driverCertInfoVo, certinfo);
        UserUpdateVo user = new UserUpdateVo();
        user.setRealname(driverCertInfoVo.getRealName());
        try {
            this.getUserService().updateById(user);
        } catch (Exception e1) {
            LOGGER.error("update user info error : {}", e1);
            throw new BusinessException("更新用户信息失败");
        }
        String idno = HYCUtils.encryptBankCard(certinfo.getIdno());
        certinfo.setIdno(idno);
        certinfo.setUpdateTime(new Date());
        certinfo.setUserId(vo.getId());
        CDriverCertinfoExample example = new CDriverCertinfoExample();
        example.createCriteria().andIdnoEqualTo(idno).andIdNotEqualTo(driverCertInfoVo.getId());
        List<CDriverCertinfo> cList = this.getCDriverCertinfoMapper().selectByExample(example);
        if (cList.size() > 0) {
            LOGGER.info("The idno information already exists");
            throw new BusinessException("身份证号已认证");
        }
        try {
            this.getCDriverCertinfoMapper().updateByPrimaryKeySelective(certinfo);
        } catch (Exception e) {
            LOGGER.error("update driverCertInfo error : {}", e);
            throw new BusinessException("更新司机信息失败");
        }
        return 0;
    }

    @Override
    public boolean verifyTheCurrentUservehicleInformationAudit(Long userId) {
        CTruckInfoExample example = new CTruckInfoExample();
        example.createCriteria().andUserIdEqualTo(userId);
        List<CTruckInfo> list = this.getCTruckInfoMapper().selectByExample(example);
        if (CollectionUtils.isEmpty(list)) {
            throw new CustomizeException(CustomizeException.Type.VEHICLE_NOT_HAS);
        }
        CTruckInfo cTruckInfo = list.get(0);
        if (TruckAuditStatusEnum.NOT_SUBMIT.getValue() == cTruckInfo.getStatus()) {
            throw new CustomizeException(CustomizeException.Type.VEHICLE_NOT_HAS);
        } else if (TruckAuditStatusEnum.AUDIT_CENTER.getValue() == cTruckInfo.getStatus()) {
            throw new CustomizeException(CustomizeException.Type.VEHICLE_CHECK_IN);
        } else if (TruckAuditStatusEnum.AUDIT_NOT_PASS.getValue() == cTruckInfo.getStatus()) {
            throw new CustomizeException(CustomizeException.Type.VEHICLE_NOT_PASS);
        }
        return true;
    }

    @Override
    public boolean verifyTheCurrentUservehicleInformationAudit(Long userId, Boolean isVeneer) {
        CTruckInfoExample example = new CTruckInfoExample();
        example.createCriteria().andUserIdEqualTo(userId).andTruckTypeEqualTo(isVeneer == null ? false : isVeneer);
        List<CTruckInfo> list = this.getCTruckInfoMapper().selectByExample(example);
        if (CollectionUtils.isEmpty(list)) {
            throw new CustomizeException(CustomizeException.Type.VEHICLE_NOT_HAS);
        }
        CTruckInfo cTruckInfo = list.get(0);
        if (TruckAuditStatusEnum.NOT_SUBMIT.getValue() == cTruckInfo.getStatus()) {
            throw new CustomizeException(CustomizeException.Type.VEHICLE_NOT_HAS);
        } else if (TruckAuditStatusEnum.AUDIT_CENTER.getValue() == cTruckInfo.getStatus()) {
            throw new CustomizeException(CustomizeException.Type.VEHICLE_CHECK_IN);
        } else if (TruckAuditStatusEnum.AUDIT_NOT_PASS.getValue() == cTruckInfo.getStatus()) {
            throw new CustomizeException(CustomizeException.Type.VEHICLE_NOT_PASS);
        }
        return true;
    }

}
